package com.zmx.patientend.view.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.bumptech.glide.Glide;
import com.zmx.patientend.BaseActivity;
import com.zmx.patientend.R;
import com.zmx.patientend.okhttp.OkHttp3ClientManager;
import com.zmx.patientend.pojo.Patient;
import com.zmx.patientend.pojo.Registration;
import com.zmx.patientend.utils.AllUtil;
import com.zmx.patientend.view.util.MySharedPreferences;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 时间：2020/5/12 14:47
 * 功能：挂号医生详情
 */
public class RegistrationDoctorDetailsActivity extends BaseActivity {

    @BindView(R.id.dc_head)
    ImageView dcHead;
    @BindView(R.id.dc_name)
    TextView dcName;
    @BindView(R.id.dc_describe)
    TextView dcDescribe;
    @BindView(R.id.jz_time)
    TextView jz_time;
    @BindView(R.id.dc_addres)
    TextView dcAddres;
    @BindView(R.id.yy_addres)
    TextView yyAddres;
    @BindView(R.id.xz_patient)
    TextView xzPatient;
    @BindView(R.id.submit)
    Button submit;
    @BindView(R.id.IdNumber)
    EditText IdNumber;
    @BindView(R.id.phone)
    EditText phone;
    @BindView(R.id.xz_layout)
    RelativeLayout xz_layout;

    private Registration registration;
    private String endtime;

    private Patient patient;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_registration_doctor_details;
    }

    @Override
    protected void initViews() {

        ButterKnife.bind(this);
        setToolbar(R.id.tool_bar);
        registration = (Registration) getIntent().getSerializableExtra("registration");
        endtime = getIntent().getStringExtra("endtime");
        dcName.setText(registration.getDoctor_name());
        dcDescribe.setText(registration.getTitle_name());
        dcAddres.setText(registration.getClass_name() + " " + registration.getHosp_name());
        Glide.with(mActivity).load(registration.getAvatar()).into(dcHead);
        yyAddres.setText(registration.getHosp_name());
        jz_time.setText(endtime);

    }

    @OnClick({R.id.xz_layout, R.id.submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.xz_layout:

                Intent intent = new Intent(mActivity, MakeAppointmentPatientsActivity.class);
                startActivityForResult(intent, 1);//带请求码打开activity (请求码自定 这里设为1

                break;
            case R.id.submit:

                if(patient == null){

                    Toast("请选择患者信息");
                    return;

                }
                //判断用户输入是否为空
                if (getAccount().isEmpty()) {

                    Toast("你输入的账号为空！");
                    return;

                }
                if (!isChinaPhoneLegal(getAccount())) {
                    Toast("输入正确的手机号码！");
                    return;
                }

                getData();

                break;
        }
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {

                case 1:

                    xzPatient.setText(patient.getPatient_name());
                    xzPatient.setEnabled(false);
                    IdNumber.setText(patient.getIdcard());
                    IdNumber.setEnabled(false);
                    phone.setText(patient.getMobile());

                    break;

                case 2:
//                {"code":1,"msg":"挂号成功","data":true}?

                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());


                        Toast(object.getString("msg"));
                        if(object.getInt("code")==1){
                            finish();
                        }


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;


            }

        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {  //根据请求码可处理不同活动返回的数据
            case 1: //返回的请求码
                //操作

                if (data != null){

                patient = (Patient) data.getSerializableExtra("patient");
                handler.sendEmptyMessage(1);

                }
                break;
        }
    }


    /**
     * 获取所有患者信息
     */
    public void getData() {

        List<String> ls = new ArrayList<>();
        ls.add(registration.getClass_id()+"");
        ls.add(registration.getDoctor_id()+"");
        ls.add(endtime);
        ls.add(registration.getHosp_id()+"");
        ls.add(patient.getPatient_id()+"");

        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "registerAdd");
        params.put("data[hosp_id]", registration.getHosp_id());
        params.put("data[class_id]", registration.getClass_id());
        params.put("data[patient_id]", patient.getPatient_id());
        params.put("data[doctor_id]",registration.getDoctor_id());
        params.put("data[endtime]", endtime);
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/app/", params, handler, 2, 404);

    }

    /**
     * 大陆手机号码11位数，匹配格式：前三位固定格式+后8位任意数
     * 此方法中前三位格式有：
     * 13+任意数
     * 145,147,149
     * 15+除4的任意数(不要写^4，这样的话字母也会被认为是正确的)
     * 166
     * 17+3,5,6,7,8
     * 18+任意数
     * 198,199
     */
    public static boolean isChinaPhoneLegal(String str) throws PatternSyntaxException {

        // ^ 匹配输入字符串开始的位置
        // \d 匹配一个或多个数字，其中 \ 要转义，所以是 \\d
        // $ 匹配输入字符串结尾的位置
        String regExp = "^((13[0-9])|(14[5,7,9])|(15[0-3,5-9])|(166)|(17[3,5,6,7,8])" +
                "|(18[0-9])|(19[8,9]))\\d{8}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(str);
        return m.matches();

    }

    /**
     * 获取手机号
     */
    public String getAccount() {
        return phone.getText().toString().trim();//去掉空格
    }

}
